﻿using LJ.Abstractions.Extensions;
using LJ.Abstractions.Pack;
using LJ.Abstractions.Pack.Attributes;
using LJ.AspNetCore.Abstractions.Pack;
using LJ.Host.Abstractions.Exceptions;
using LJ.Host.Abstractions.Pack;
using LJ.Host.Web.Middleware;
using LJ.Host.Web.Pack;
using Microsoft.AspNetCore.HttpOverrides;

namespace LJ.Host.Web.Extensions;

public static class WebApplicationExtensions
{
    public static WebApplication UseLJ(this WebApplication webApplication)
    {

        //代理转发
        webApplication.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });

        //配置跨域资源共享
        webApplication.UseCors();

        webApplication.UseMiddleware<HybridServiceMiddleware>();

        var packProvider = new AspNetCorePackProvider(webApplication);

        var packManager = webApplication.Services.GetRequiredService<IPackManager>();


        packProvider.Logger.LogInformation("---------------------");
        packProvider.Logger.LogInformation("Load LJ");

        var packs = packManager.GetPacks();
        foreach (var pack in packs)
        {
            pack.Use(packProvider);

            var packType = pack.GetType();
            var packAttributes = packType.GetAttributes<PackAttribute>();
            if (packAttributes.Where(a => a.PackType == PackType.Web).Any())
            {
                if (pack is IAspNetCorePack aspNetCorePack)
                {
                    aspNetCorePack.Use(packProvider);
                }
                else
                {
                    throw new PackException($"加载模块{packType.FullName}时无法找到依赖模块");
                }
            }

            packProvider.Logger.LogInformation("Load Pack:{name}", pack.GetType().Name);
        }
        packProvider.Logger.LogInformation("Load Pack Ok");
        packProvider.Logger.LogInformation("---------------------");

        return webApplication;
    }
}
